<script setup lang="ts">
import { computed, reactive,  watch } from 'vue';
import { useLoading } from '@sa/hooks';
import { fetchCreateSingleTransfer, fetchUpdateSingleTransfer } from '@/service/api/business/single-transfer';
import { uploadFile } from '@/service/api/business/system-config';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'SingleTransferOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Business.SingleTransfer | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const { loading: submitLoading, startLoading: startSubmitLoading, endLoading: endSubmitLoading } = useLoading();
const { loading: uploadLoading, startLoading: startUploadLoading, endLoading: endUploadLoading } = useLoading();
const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增单笔转账配置',
    edit: '编辑单笔转账配置'
  };
  return titles[props.operateType];
});

type Model = Api.Business.SingleTransferOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    appId: '',
    privateKey: '',
    alipayPublicKey: '',
    notifyUrl: '',
    status: 0,
    username: '',
    password: '',
    appCertPath: '',
    alipayPublicCertPath: '',
    rootCertPath: ''

  };
}

type RuleKey = Extract<keyof Model, 'appId' | 'privateKey' | 'alipayPublicKey' | 'notifyUrl' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule | App.Global.FormRule[]> = {
  appId: createRequiredRule('应用ID不能为空'),
  privateKey: createRequiredRule('私钥不能为空'),
  alipayPublicKey: createRequiredRule('支付宝公钥不能为空'),
  notifyUrl: createRequiredRule('回调地址不能为空'),
  status: createRequiredRule('启用状态不能为空')
};

// 文件上传处理
async function handleFileUpload(event: Event, field: keyof Model) {
  const input = event.target as HTMLInputElement;
  if (!input.files || input.files.length === 0) return;

  const file = input.files[0];
  startUploadLoading();

  try {
    const { error, data } = await uploadFile(file);
    if (!error && data) {
      model[field] = data.fileUrl;
      window.$message?.success('文件上传成功');
    } else {
      window.$message?.error('文件上传失败');
    }
  } catch (error) {
    console.error('文件上传错误:', error);
    window.$message?.error('文件上传失败');
  } finally {
    endUploadLoading();
    input.value = ''; // 清空文件选择
  }
}

// 触发文件选择
function triggerFileInput(field: keyof Model) {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.pem,.key,.crt,.txt,.cer'; // 限制上传证书文件类型
  input.onchange = (event) => handleFileUpload(event, field);
  input.click();
}

// 查看文件
function viewFile(fileUrl: string) {
  if (fileUrl) {
    window.open(fileUrl, '_blank');
  }
}

// 删除文件
function removeFile(field: keyof Model) {
  model[field] = '';
}


function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
    // 编辑时不需要用户名和密码
    model.username = '';
    model.password = '';
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  startSubmitLoading();

  try {
    if (props.operateType === 'add') {
      const {
        appId,
        privateKey,
        alipayPublicKey,
        notifyUrl,
        status,
        username,
        password,
        alipayPublicCertPath,
        rootCertPath,
        appCertPath
      } = model;
      const { error } = await fetchCreateSingleTransfer({
        appId,
        privateKey,
        alipayPublicKey,
        notifyUrl,
        status,
        username,
        password,
        alipayPublicCertPath,
        rootCertPath,
        appCertPath
      });
      if (error) return;
    }

    if (props.operateType === 'edit') {
      const { id, appId, privateKey, alipayPublicKey, notifyUrl, status } = model;
      const { error } = await fetchUpdateSingleTransfer({
        id,
        appId,
        privateKey,
        alipayPublicKey,
        notifyUrl,
        status
      });
      if (error) return;
    }

    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  } catch (error) {
    console.error('操作失败:', error);
  } finally {
    endSubmitLoading();
  }
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="600" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NDivider>基础配置</NDivider>

        <NFormItem label="应用ID" path="appId">
          <NInput v-model:value="model.appId" placeholder="请输入支付宝应用ID" />
        </NFormItem>

<!--        <NFormItem label="回调地址" path="notifyUrl">-->
<!--          <NInput v-model:value="model.notifyUrl" placeholder="请输入异步通知回调地址" />-->
<!--        </NFormItem>-->

        <NDivider>密钥配置</NDivider>

        <NFormItem label="应用私钥" path="privateKey">
          <NInput
            v-model:value="model.privateKey"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6 }"
            placeholder="请输入应用私钥内容"
          />
        </NFormItem>

        <NFormItem label="应用公钥证书">
          <div class="flex items-center gap-2">
            <NButton :loading="uploadLoading" @click="triggerFileInput('appCertPath')">
              选择文件
            </NButton>
            <span v-if="model.appCertPath" class="text-green-600">已上传</span>
            <NButton v-if="model.appCertPath" text type="primary" @click="viewFile(model.appCertPath)">
              查看
            </NButton>
            <NButton v-if="model.appCertPath" text type="error" @click="removeFile('appCertPath')">
              删除
            </NButton>
          </div>
        </NFormItem>

        <NFormItem label="支付宝公钥证书">
          <div class="flex items-center gap-2">
            <NButton :loading="uploadLoading" @click="triggerFileInput('alipayPublicCertPath')">
              选择文件
            </NButton>
            <span v-if="model.alipayPublicCertPath" class="text-green-600">已上传</span>
            <NButton
              v-if="model.alipayPublicCertPath"
              text
              type="primary"
              @click="viewFile(model.alipayPublicCertPath)"
            >
              查看
            </NButton>
            <NButton v-if="model.alipayPublicCertPath" text type="error" @click="removeFile('alipayPublicCertPath')">
              删除
            </NButton>
          </div>
        </NFormItem>

        <NFormItem label="根证书证书">
          <div class="flex items-center gap-2">
            <NButton :loading="uploadLoading" @click="triggerFileInput('rootCertPath')">
              选择文件
            </NButton>
            <span v-if="model.rootCertPath" class="text-green-600">已上传</span>
            <NButton
              v-if="model.rootCertPath"
              text
              type="primary"
              @click="viewFile(model.rootCertPath)"
            >
              查看
            </NButton>
            <NButton v-if="model.rootCertPath" text type="error" @click="removeFile('rootCertPath')">
              删除
            </NButton>
          </div>
        </NFormItem>


        <NDivider>状态设置</NDivider>
        <NFormItem label="启用状态" path="status">
          <DictRadio v-model:value="model.status" dict-code="sys_normal_disable" />
        </NFormItem>

      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped>
.flex-center {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>
